/*
 * Indexer.java
 *
 * Created on July 31, 2007, 8:55 PM
 *
 * To change this template, choose Tools | Template Manager
 * and open the template in the editor.
 */
package com.afaker.rss.search;

import com.afaker.rss.context.ResourceContext;
import com.afaker.rss.feed.biz.FeedFetcher;
import com.afaker.rss.feed.EntrySet;
import com.afaker.rss.gui.action.MenuAction;
import com.afaker.rss.gui.table.XMLTableModel;
import com.sun.syndication.io.FeedException;
import com.afaker.rss.xml.XMLDocumentFactory;
import java.io.File;
import java.io.IOException;
import java.util.Iterator;
import org.apache.lucene.analysis.standard.StandardAnalyzer;
import org.apache.lucene.document.DateTools;
import org.apache.lucene.document.Document;
import org.apache.lucene.document.Field;
import org.apache.lucene.index.CorruptIndexException;
import org.apache.lucene.index.IndexWriter;
import org.apache.lucene.store.LockObtainFailedException;

/**
 *
 * @author bruce
 */
public class Indexer {

    public static final String CATEGORY_FIELD = "category";
    public static final String MODIFIED_FIELD = "modified";
    public static final String PATH_FIELD = "path";
    public static final String SUMMARY_FIELD = "summary";
    public static final String TITLE_FIELD = "title";
    private IndexWriter writer;
    /** Creates a new instance of Indexer */
    private static final String INDEX_DIR = ResourceContext.getResourceContext().getProperty("index.dir");
    private XMLTableModel model = new XMLTableModel();
    private XMLDocumentFactory xml = new XMLDocumentFactory();
    private String file;
    private FeedFetcher fetcher;

    public Indexer() {
    }

    public void index(String file) {
        xml.build(ResourceContext.getResourceContext().getProperty("favorite.file"));
        File indexFile = new File(INDEX_DIR);
        boolean isCreated = false;
        if (indexFile.isDirectory()) {
            int length = indexFile.listFiles().length;
            if (length < 2) {
                isCreated = true;
            }
        }
        try {
            writer = new IndexWriter(INDEX_DIR, new StandardAnalyzer(), isCreated);
        } catch (LockObtainFailedException ex) {
            ex.printStackTrace();
        } catch (IOException ex) {
            ex.printStackTrace();
        }
        index(new File(file));
        try {
            writer.optimize();
        } catch (CorruptIndexException ex) {
            ex.printStackTrace();
        } catch (IOException ex) {
            ex.printStackTrace();
        }
        try {
            writer.close();
        } catch (CorruptIndexException ex) {
            ex.printStackTrace();
        } catch (IOException ex) {
            ex.printStackTrace();
        }
    }

    private void index(File file) {
        File files[];
        if (file.isDirectory()) {
            files = file.listFiles();
            for (int i = 0; i < files.length; i++) {
                index(files[i]);
            }
        } else {
            System.out.println("Indexing " + file.getPath());
            addFeedInfoField(file);
        }
    }

    public void addFeedInfoField(File file) {
        Document doc;
        try {
            model.setNullData();
            model.getFeed(file.getCanonicalPath());
            model.addEntries();
        //model.setDataSource(file.getCanonicalPath(),false);
        } catch (FeedException ex) {
            ex.printStackTrace();
        } catch (IOException ex) {
            ex.printStackTrace();
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        String buffer;
        EntrySet set = model.getEntrySet();
        for (int i = 0; i < set.size(); i++) {
            buffer = set.getEntry(i).toString();
            doc = new Document();
            try {
                doc.add(new Field(PATH_FIELD, file.getCanonicalPath(), Field.Store.YES, Field.Index.UN_TOKENIZED));
            } catch (IOException ex) {
                ex.printStackTrace();
            }
            String category = getAllCategory();
            doc.add(new Field(CATEGORY_FIELD, category, Field.Store.YES, Field.Index.UN_TOKENIZED));
            doc.add(new Field(TITLE_FIELD, set.getEntry(i).getTitle(), Field.Store.YES, Field.Index.TOKENIZED));
            doc.add(new Field(MODIFIED_FIELD,
                    DateTools.timeToString(file.lastModified(), DateTools.Resolution.MINUTE),
                    Field.Store.YES, Field.Index.UN_TOKENIZED));
            doc.add(new Field(SUMMARY_FIELD, buffer, Field.Store.YES, Field.Index.TOKENIZED));
            try {
                writer.addDocument(doc);
            } catch (CorruptIndexException ex) {
                ex.printStackTrace();
            } catch (IOException ex) {
                ex.printStackTrace();
            }
        }
    }

    public String getAllCategory() {
        StringBuffer buffer = new StringBuffer();
        org.jdom.Element root = xml.getRootElement();
        org.jdom.Element favorite = root.getChild(MenuAction.FAVORITE_NODE_NAME);
        org.jdom.Element element = getElement(favorite);
        if (element == null) {
            return "";
        }
        buffer.append(element.getAttributeValue(MenuAction.FEEDNAME_ATTRIBUTE_NAME) + ",");
        element = element.getParentElement();
        while (!element.isRootElement()) {
            buffer.append(element.getAttributeValue(
                    MenuAction.FAVORITE_N_CATEGORY_NAME_ATTRIBUTE_NAME) + ",");
            element = element.getParentElement();
        }
        String[] s = buffer.toString().split(",");
        String str = "";
        for (int i = s.length - 1; i >= 0; i--) {
            str += s[i] + ",";
        }
        return str;
    }

    public org.jdom.Element getElement(org.jdom.Element root) {
        org.jdom.Element element;
        Iterator it0 = root.getChildren(MenuAction.CHANNEL_NODE_NAME).listIterator();
        while (it0.hasNext()) {
            element = (org.jdom.Element) it0.next();
            if (element.getAttributeValue(
                    MenuAction.FEEDNAME_ATTRIBUTE_NAME).equals(model.getFeedTitle())) {
                return element;
            }
        }
        Iterator it1 = root.getChildren(MenuAction.CATEGORY_NODE_NAME).listIterator();
        while (it1.hasNext()) {
            element = (org.jdom.Element) it1.next();
            return getElement(element);
        }
        return null;
    }

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        // TODO code application logic here
        Indexer in = new Indexer();

    }
}
